/*
 * Copyright 2009 Armando Blancas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package taskgraph.tasks.io;

import java.beans.IntrospectionException;
import java.io.EOFException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import taskgraph.ports.InputPort;
import taskgraph.reflect.Accessor;
import taskgraph.reflect.BeanMetadata;
import taskgraph.tasks.PrimitiveTask;


/**
 * Source task for JDBC SQL Insert with object data.
 *  
 * @author Armando Blancas
 * @see taskgraph.ports.InputPort
 * @param <E> The type of elements read by this task.
 */
public class JDBCInsert<E> extends PrimitiveTask {

	private InputPort<E> input;
	private String sqlURL;
	private String sqlUser;
	private String sqlPassword;

	/**
	 * This constructor allows creating instances as beans.
	 */
    public JDBCInsert() {
    	// do nothing
    }

    /**
     * JDBCInsert constructor.
     * 
     * @param input  The element input port.
     * @param sqlURL The JDBC URL that identifies the database.
     */
    public JDBCInsert(final InputPort<E> input, final String sqlURL) {
    	setInput(input);
    	setSqlURL(sqlURL);
    }
    
    /**
     * JDBCInsert constructor.
     * 
     * @param input       The element input port.
     * @param sqlURL      The JDBC URL that identifies the database.
     * @param sqlUser     The database user account name.
     * @param sqlPassword The database user account password.
     */
    public JDBCInsert(final InputPort<E> input,
    	              final String sqlURL,
    	              final String sqlUser,
    	              final String sqlPassword) {
    	setInput(input);
    	setSqlURL(sqlURL);
    	setSqlUser(sqlUser);
    	setSqlPassword(sqlPassword);
    }
    
	/**
     * Gets the input port.
     * 
	 * @return The element input port.
	 */
	public InputPort<E> getInput() {
		return input;
	}

	/**
	 * Gets the database account password.
	 * 
	 * @return The password for the give user.
	 */
	public String getSqlPassword() {
		return sqlPassword;
	}

	/**
	 * Gets the database identification string.
	 * 
	 * @return The database URL.
	 */
	public String getSqlURL() {
		return sqlURL;
	}

	/**
	 * Gets the database user name.
	 * 
	 * @return The user string value.
	 */
	public String getSqlUser() {
		return sqlUser;
	}
	
	private String getInsertCommand(String table, Accessor[] accessors) {
		StringBuilder stmt = new StringBuilder("INSERT INTO ");
		stmt.append(table)
		    .append('(')
		    .append(accessors[0].getPropertyName());
		for (int i = 1; i < accessors.length; i++) {
			stmt.append(',')
			    .append(accessors[i].getPropertyName());
		}
		
		stmt.append(") VALUES (");
		stmt.append('?');
		for (int i = 1; i < accessors.length; i++) {
			stmt.append(',')
			    .append('?');
		}		
		stmt.append(')');
		return stmt.toString();
	}

	/**
     * Performs the work of this task.
 	 */
    public void run() {
    	try {
    		E element = input.read();
    		Class<?> clazz = element.getClass();
    		String table = BeanMetadata.getEntity(clazz);
    		if (table == null) {
                log.warn("JDBCInsert#run(): No table defined");
                return;
    		}    		
    		
    		Connection connection = 
    			DriverManager.getConnection(sqlURL, sqlUser, sqlPassword);    		
    		String query = String.format("SELECT * FROM %s", table);
    		Statement queryStatement = connection.createStatement();
    		ResultSet set = queryStatement.executeQuery(query);

    		Accessor[] accessors = BeanMetadata.extractGetters(clazz, set);
    		if (accessors.length == 0) {
                log.warn("JDBCInsert#run(): No getters defined");
                return;
    		}
    		
    		String sqlCommand = getInsertCommand(table, accessors);
    		PreparedStatement statement = 
    			connection.prepareStatement(sqlCommand);

    		while (!Thread.currentThread().isInterrupted()) {
    			for (int i = 0; i < accessors.length; i++) {
    				Accessor accessor = accessors[i];
    				Method get = accessor.getMethod();
    				Object value = get.invoke(element);
    				statement.setObject(i+1, value);
    			}
        		statement.executeUpdate();
        		element = input.read();
            }
        } catch (InterruptedIOException e) {
        	// interruption request
		} catch (SQLException e) {
            log.error("JDBCInsert#run()", e);
        } catch (EOFException e) {
        	// we're done reading
        } catch (IOException e) {
            log.error("JDBCInsert#run()", e);
		} catch (IllegalAccessException e) {
            log.error("JDBCInsert#run()", e);
		} catch (IntrospectionException e) {
            log.error("JDBCInsert#run()", e);
		} catch (IllegalArgumentException e) {
            log.error("JDBCInsert#run()", e);
		} catch (InvocationTargetException e) {
            log.error("JDBCInsert#run()", e);
		} finally {
			input.close();
        }
    }

	/**
	 * Sets the input port.
	 * 
	 * @param input The element input port.
	 */
    public void setInput(final InputPort<E> input) {
    	if (input == null)
    		throw new IllegalArgumentException("input == null");
 		this.input = input;
	}

    /**
	 * Gets the database account password for the user name.
	 * 
	 * @param sqlPassword The string password to set.
	 */
	public void setSqlPassword(final String sqlPassword) {
    	if (sqlPassword == null)
    		throw new IllegalArgumentException("sqlPassword == null");
		this.sqlPassword = sqlPassword;
	}

	/**
	 * Sets the database identification string.
	 * 
	 * @param sqlURL The URL string to set.
	 */
	public void setSqlURL(String sqlURL) {
    	if (sqlURL == null)
    		throw new IllegalArgumentException("sqlURL == null");
		this.sqlURL = sqlURL;
	}

	/**
	 * Sets the database user name.
	 * 
	 * @param sqlUser The user string value to set.
	 */
	public void setSqlUser(String sqlUser) {
    	if (sqlUser == null)
    		throw new IllegalArgumentException("sqlUser == null");
		this.sqlUser = sqlUser;
	}

}
